<template>
  <div>
    <div>
      <t-checkbox :checked="checkAll" :indeterminate="indeterminate" :on-change="(checked) => handleSelectAll(checked, index)">{{ item.group }}</t-checkbox>
    </div>
    <t-checkbox-group v-model="permissionSelected" :options="item.children" @change="onChange1" />
  </div>
</template>
<script setup>
import { ref, watch, computed, defineEmits } from 'vue'
const emit = defineEmits(['selected'])
const props = defineProps({
  item: {
    type: Object,
    default: () => ({})
  },
  defaultValue: {
    type: Array,
    default: () => []
  }
})
// 搜集所有权限，用于全选判断
const optionsAll = props.item.children.map(it => it.label)
// 已选项
const permissionSelected = ref(props.defaultValue)
watch(() => props.defaultValue, (val) => {
  permissionSelected.value = val
})
// 是否全选
const checkAll = computed(() => permissionSelected.value.length === optionsAll.length)
// 是否展示半选
const indeterminate = computed(() => !!(optionsAll.length > permissionSelected.value.length && permissionSelected.value.length))

// 全选事件
const handleSelectAll = (checked) => {
  permissionSelected.value = checked ? optionsAll : []
  emit('selected', permissionSelected.value)
}
// 勾选单一项事件
const onChange1 = (val) => {
  emit('selected', permissionSelected.value)
}

</script>
